<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>帮助内容编辑器</title>
  <style>
    /* 隐藏滚动条 */
    body {
      overflow: -moz-scrollbars-none;
      -ms-overflow-style: none;
      scrollbar-width: none;
    }

    body::-webkit-scrollbar {
      display: none;
    }

    ::-webkit-scrollbar {
      width: 0px;
      height: 5px;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      user-select: none;
    }

    body {
      padding: 20px 20px 20px 20px;
      font-family: "OPSans";
      font-size: 16px;
      color: #1e1f20;
      transform: scale(1.5);
      transform-origin: 0 0;
      width: 788px;
      background-image: url('https://ts1.tc.mm.bing.net/th/id/R-C.62e400952021986fcdb4cb889e19aed6?rik=bvvbTIAOxNLjAg&riu=http%3a%2f%2fpic.rmb.bdstatic.com%2f62e400952021986fcdb4cb889e19aed6.jpeg&ehk=RB1Inb6x0puc36Q%2bU9UrDdcv7JB2Rwm08lUv4h0BnCY%3d&risl=&pid=ImgRaw&r=0');
    }

    .container {
      width: 788px;
      padding: 15px 15px 5px 15px;
    }

    bq {
      margin-left: 335px;
      text-align: center;
      color: #d2d2d2;
      font-size: 12px;
      font-weight: bold;
    }

    .head_box {
      border-radius: 15px;
      font-family: HYWenHei;
      padding: 20px 15px;
      position: relative;
      box-shadow: 0 5px 10px 0 rgb(0 0 0 / 15%);
      background: rgba(169, 169, 169, 0.1);
      backdrop-filter: blur(10px);
    }

    .head_box .id_text {
      margin-left: 20px;
      font-size: 24px;
    }

    .head_box .day_text {
      margin-left: 20px;
      font-size: 20px;
    }

    .data_box {
      padding-left: 20px;
      border-radius: 15px;
      margin-top: 20px;
      margin-bottom: 15px;
      padding: 20px 0px 5px 0px;
      background: rgba(169, 169, 169, 0.1);
      box-shadow: 0 5px 10px 0 rgb(0 0 0 / 15%);
      position: relative;
      backdrop-filter: blur(10px);
    }

    .tab_lable {
      position: absolute;
      top: -10px;
      left: -8px;
      background: #d4b98c;
      color: #d4b98c;
      font-size: 14px;
      padding: 3px 10px;
      border-radius: 15px 0px 15px 15px;
      z-index: 20;
    }

    .list {
      padding-left: 20px;
      padding-right: 0px;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      gap: 5px;
    }

    .list .item {
      display: flex;
      align-items: center;
      background: #f1f1f1;
      padding: 8px 6px 8px 6px;
      border-radius: 8px;
      margin: 10px 0px 10px 0px;
      position: relative;
    }

    .list .item .icon {
      width: 35px;
      height: 35px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: relative;
      flex-shrink: 0;
      margin-left: 10px;
      margin-right: 5px;
      cursor: pointer;
    }

    .list .item .title {
      font-size: 16px;
      margin-left: 6px;
      line-height: 20px;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-rendering: optimizeLegibility;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
    }

    .list .item .title .dec {
      font-size: 12px;
      color: #999;
      margin-top: 2px;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-rendering: optimizeLegibility;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .list .item .remove-item-button {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: #ff4d4d;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 2px 6px;
      cursor: pointer;
    }

    .list .item .remove-item-button:hover {
      background: #cc0000;
    }

    .logo {
      font-size: 14px;
      font-family: "HYWenHei";
      text-align: center;
      color: #fff;
      background: rgba(169, 169, 169, 0.3);
      backdrop-filter: blur(10px);
      padding: 10px;
      border-radius: 8px;
      font-weight: bold;
    }

    /* 可编辑样式 */
    [contenteditable="true"] {
      outline: 2px solid #007bff;
      padding: 2px;
      border-radius: 4px;
      background: rgba(255, 255, 255, 0.9);
    }

    /* 新增和移除按钮样式 */
    .group-controls {
      position: absolute;
      right: 10px;
      bottom: 10px;
      display: flex;
      gap: 5px;
    }

    .group-controls button {
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 5px 10px;
      cursor: pointer;
    }

    .group-controls button:hover {
      background: #0056b3;
    }

    .add-list-button {
      text-align: center;
      margin-top: 10px;
    }

    .add-list-button button {
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 5px 10px;
      cursor: pointer;
    }

    .add-list-button button:hover {
      background: #0056b3;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .modal-content {
      background: white;
      padding: 20px;
      border-radius: 8px;
      width: 80%;
      max-width: 600px;
    }

    .icon-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 10px;
    }

    .icon-grid img {
      width: 50px;
      height: 50px;
      cursor: pointer;
      border: 2px solid transparent;
      border-radius: 4px;
    }

    .icon-grid img:hover {
      border-color: #007bff;
    }

    .close-modal {
      text-align: right;
      margin-bottom: 10px;
    }

    .close-modal button {
      background: #ff4d4d;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 5px 10px;
      cursor: pointer;
    }

    .close-modal button:hover {
      background: #cc0000;
    }

    /* 移动按钮样式 */
    .move-item-left,
    .move-item-right {
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 2px 6px;
      cursor: pointer;
      margin-right: 5px; /* 与 - 号按钮的间距 */
    }

    .move-item-left:hover,
    .move-item-right:hover {
      background: #0056b3;
    }

    /* 调整 - 号按钮的位置 */
    .remove-item-button {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: #ff4d4d;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 2px 6px;
      cursor: pointer;
    }

    .remove-item-button:hover {
      background: #cc0000;
    }

    /* 调整移动按钮的位置 */
    .item-controls {
      position: absolute;
      right: 30px; /* 与 - 号按钮的间距 */
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      gap: 5px;
    }

    /* 配置表单样式 */
    .config-form {
      margin-top: 20px;
      padding: 20px;
      background: rgba(169, 169, 169, 0.1);
      border-radius: 15px;
      backdrop-filter: blur(10px);
    }

    .config-form label {
      display: block;
      margin-top: 10px;
    }

    .config-form input {
      width: 100%;
      padding: 5px;
      margin-top: 5px;
      border-radius: 4px;
      border: 1px solid #ccc;
    }

    .config-form button {
      margin-top: 10px;
      padding: 5px 10px;
      background: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .config-form button:hover {
      background: #0056b3;
    }
  </style>
</head>
<body>
  <div class="container" id="container">
    <div class="head_box">
      <div class="id_text">帮助编辑器</div>
      <h2 class="day_text">实时预览</h2>
    </div>
    <div id="previewContent"></div>
    <div id="hitokoto" class="logo"></div>
  </div>
  <bq>©Jiaozi 2025 Help-Lite</bq>

  <!-- 配置表单 -->
  <div class="config-form">
    <h2>配置编辑器</h2>
    <form id="configForm">
      <label for="main_title">主标题:</label>
      <input type="text" id="main_title" name="main_title" placeholder="Yunzai-Bot"><br>

      <label for="sub_title">副标题:</label>
      <input type="text" id="sub_title" name="sub_title" placeholder="帮助详情"><br>

      <label for="columns">列数:</label>
      <input type="number" id="columns" name="columns" placeholder="4"><br>

      <label for="device_scale_factor">渲染精度:</label>
      <input type="number" step="0.1" id="device_scale_factor" name="device_scale_factor" placeholder="1.1"><br>

      <label for="default_hitokoto">默认一言:</label>
      <input type="text" id="default_hitokoto" name="default_hitokoto" placeholder="种自己的花，爱自己的宇宙"><br>

      <label for="background_image_url">背景图片 URL:</label>
      <input type="text" id="background_image_url" name="background_image_url" placeholder="none"><br>

      <button type="button" onclick="saveConfig()">保存配置</button>
    </form>
  </div>

  <!-- 图标选择模态框 -->
  <div id="iconModal" class="modal">
    <div class="modal-content">
      <div class="close-modal">
        <button onclick="closeModal()">关闭</button>
      </div>
      <div class="icon-grid" id="iconGrid"></div>
    </div>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/js-yaml@4.1.0/dist/js-yaml.min.js"></script>
  <script>
    // 初始数据
    let helpData = [];
    let config = {
      main_title: 'Yunzai-Bot',
      sub_title: '帮助详情',
      columns: 4,
      device_scale_factor: 1.1,
      default_hitokoto: '种自己的花，爱自己的宇宙',
      background_image_url: 'none',
    };
    let currentGroupIndex = null;
    let currentItemIndex = null;

    // 加载 help.yaml 文件内容
    async function loadYaml() {
      try {
        const response = await fetch('/help.yaml');
        if (!response.ok) {
          throw new Error(`HTTP 错误！状态码: ${response.status}`);
        }
        const yamlText = await response.text();
        helpData = jsyaml.load(yamlText) || [];
        renderPreview();
      } catch (error) {
        console.error('加载 YAML 文件失败:', error);
        alert('加载 YAML 文件失败，请检查文件路径和内容！');
      }
    }

    // 加载 config.yaml 文件内容
    async function loadConfig() {
      try {
        const response = await fetch('/config.yaml');
        if (!response.ok) {
          throw new Error(`HTTP 错误！状态码: ${response.status}`);
        }
        const yamlText = await response.text();
        config = jsyaml.load(yamlText) || config;

        // 填充表单
        document.getElementById('main_title').value = config.main_title || '';
        document.getElementById('sub_title').value = config.sub_title || '';
        document.getElementById('columns').value = config.columns || 4;
        document.getElementById('device_scale_factor').value = config.device_scale_factor || 1.1;
        document.getElementById('default_hitokoto').value = config.default_hitokoto || '';
        document.getElementById('background_image_url').value = config.background_image_url || 'none';

        // 更新页面内容
        renderPreview();
      } catch (error) {
        console.error('加载 config.yaml 文件失败:', error);
      }
    }

    // 保存 config.yaml 文件内容
    async function saveConfig() {
      const config = {
        main_title: document.getElementById('main_title').value,
        sub_title: document.getElementById('sub_title').value,
        columns: parseInt(document.getElementById('columns').value),
        device_scale_factor: parseFloat(document.getElementById('device_scale_factor').value),
        default_hitokoto: document.getElementById('default_hitokoto').value,
        background_image_url: document.getElementById('background_image_url').value,
      };

      const yamlText = jsyaml.dump(config);
      const response = await fetch('/config.yaml', {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: yamlText,
      });

      if (response.ok) {
        alert('配置保存成功！');
      } else {
        alert('配置保存失败！');
      }
    }

    // 渲染预览内容
    function renderPreview() {
      const previewContent = document.getElementById('previewContent');
      previewContent.innerHTML = generatePreviewHTML(helpData);

      // 更新主标题和副标题
      const mainTitle = document.querySelector('.id_text');
      const subTitle = document.querySelector('.day_text');
      mainTitle.textContent = config.main_title || '帮助编辑器';
      subTitle.textContent = config.sub_title || '实时预览';

      // 更新背景图片
      const body = document.querySelector('body');
      if (config.background_image_url && config.background_image_url !== 'none') {
        body.style.backgroundImage = `url('${config.background_image_url}')`;
      } else {
        body.style.backgroundImage = 'none';
      }

      // 为可编辑元素绑定事件
      document.querySelectorAll('[contenteditable="true"]').forEach(element => {
        element.addEventListener('blur', updateData);
      });

      // 为图标绑定点击事件
      document.querySelectorAll('.icon').forEach(icon => {
        icon.addEventListener('click', () => {
          currentGroupIndex = icon.getAttribute('data-group-index');
          currentItemIndex = icon.getAttribute('data-item-index');
          openModal();
        });
      });

      // 为新增和移除按钮绑定事件
      document.querySelectorAll('.add-group-button').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          const groupName = prompt('请输入新组的名称：');
          if (groupName) {
            // 在当前 group 下方新增一个 group
            helpData.splice(groupIndex + 1, 0, { group: groupName, list: [] });
            renderPreview();
            saveData();
          }
        });
      });

      document.querySelectorAll('.remove-group-button').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          helpData.splice(groupIndex, 1);
          renderPreview();
          saveData();
        });
      });

      document.querySelectorAll('.add-list-button button').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          const newItem = { icon: 'default', title: '新标题', desc: '新描述' };
          helpData[groupIndex].list.push(newItem);
          renderPreview();
          saveData();
        });
      });

      document.querySelectorAll('.remove-item-button').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          const itemIndex = button.getAttribute('data-item-index');
          helpData[groupIndex].list.splice(itemIndex, 1);
          renderPreview();
          saveData();
        });
      });

      // 为 < 和 > 按钮绑定事件
      document.querySelectorAll('.move-item-left').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          const itemIndex = button.getAttribute('data-item-index');
          moveItemLeft(groupIndex, itemIndex);
        });
      });

      document.querySelectorAll('.move-item-right').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          const itemIndex = button.getAttribute('data-item-index');
          moveItemRight(groupIndex, itemIndex);
        });
      });

      // 为 ↑ 和 ↓ 按钮绑定事件
      document.querySelectorAll('.move-group-up').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          moveGroupUp(groupIndex);
        });
      });

      document.querySelectorAll('.move-group-down').forEach(button => {
        button.addEventListener('click', () => {
          const groupIndex = button.getAttribute('data-group-index');
          moveGroupDown(groupIndex);
        });
      });
    }

    // 生成预览 HTML
    function generatePreviewHTML(data) {
      let html = '';
      const itemWidth = `calc(${100 / config.columns}% - 10px)`;

      data.forEach((group, groupIndex) => {
        html += `
          <div class="data_box">
            <div class="tab_lable" contenteditable="true" data-group-index="${groupIndex}" data-field="group">${group.group}</div>
            <div class="group-controls">
              <button class="move-group-up" data-group-index="${groupIndex}">↑</button>
              <button class="move-group-down" data-group-index="${groupIndex}">↓</button>
              <button class="add-group-button" data-group-index="${groupIndex}">+</button>
              <button class="remove-group-button" data-group-index="${groupIndex}">-</button>
            </div>
            <div class="list">
        `;

        group.list.forEach((item, itemIndex) => {
          html += `
            <div class="item" style="width: ${itemWidth}">
              <img class="icon" src="icon/${item.icon}.png" data-group-index="${groupIndex}" data-item-index="${itemIndex}" />
              <div class="title">
                <div class="text" contenteditable="true" data-group-index="${groupIndex}" data-item-index="${itemIndex}" data-field="title">${item.title}</div>
                <div class="dec" contenteditable="true" data-group-index="${groupIndex}" data-item-index="${itemIndex}" data-field="desc">${item.desc}</div>
              </div>
              <div class="item-controls">
                <button class="move-item-left" data-group-index="${groupIndex}" data-item-index="${itemIndex}"><</button>
                <button class="move-item-right" data-group-index="${groupIndex}" data-item-index="${itemIndex}">></button>
              </div>
              <button class="remove-item-button" data-group-index="${groupIndex}" data-item-index="${itemIndex}">-</button>
            </div>
          `;
        });

        html += `
            </div>
            <div class="add-list-button">
              <button data-group-index="${groupIndex}">+ 新增卡片</button>
            </div>
          </div>
        `;
      });

      // 添加新增组的按钮
      html += `
        <div class="data_box">
          <div class="add-list-button">
            <button class="add-group-button" data-group-index="${helpData.length}">+ 新增组</button>
          </div>
        </div>
      `;

      return html;
    }

    // 更新数据
    function updateData(event) {
      const target = event.target;
      const groupIndex = target.getAttribute('data-group-index');
      const itemIndex = target.getAttribute('data-item-index');
      const field = target.getAttribute('data-field');
      const newValue = target.innerText;

      if (field === 'group') {
        // 更新组名
        helpData[groupIndex].group = newValue;
      } else {
        // 更新项目
        helpData[groupIndex].list[itemIndex][field] = newValue;
      }

      // 保存数据
      saveData();
    }

    // 保存数据
    async function saveData() {
      const yamlText = jsyaml.dump(helpData, {
        forceQuotes: true, // 强制所有字符串使用引号
        quotingType: "'",  // 使用单引号
        lineWidth: -1,     // 禁用换行
      });
      const response = await fetch('/help.yaml', {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: yamlText,
      });
      if (response.ok) {
        console.log('数据已保存！');
      } else {
        console.error('保存失败！');
      }
    }

    // 打开图标选择模态框
    function openModal() {
      const modal = document.getElementById('iconModal');
      const iconGrid = document.getElementById('iconGrid');
      iconGrid.innerHTML = '';

      // 加载图标列表
      fetch('/icon-list')
        .then(response => response.json())
        .then(icons => {
          icons.forEach(icon => {
            const img = document.createElement('img');
            img.src = `icon/${icon}`;
            img.addEventListener('click', () => {
              helpData[currentGroupIndex].list[currentItemIndex].icon = icon.replace('.png', '');
              renderPreview();
              saveData();
              closeModal();
            });
            iconGrid.appendChild(img);
          });
        });

      modal.style.display = 'flex';
    }

    // 关闭模态框
    function closeModal() {
      const modal = document.getElementById('iconModal');
      modal.style.display = 'none';
    }

    // 向左移动项目
    function moveItemLeft(groupIndex, itemIndex) {
      if (itemIndex > 0) {
        const item = helpData[groupIndex].list.splice(itemIndex, 1)[0];
        helpData[groupIndex].list.splice(itemIndex - 1, 0, item);
        renderPreview();
        saveData();
      } else if (groupIndex > 0) {
        const confirmMove = confirm('是否将此项目移动到上一个组？');
        if (confirmMove) {
          const item = helpData[groupIndex].list.splice(itemIndex, 1)[0];
          helpData[groupIndex - 1].list.push(item);
          renderPreview();
          saveData();
        }
      } else {
        alert('已经在最前面，无法继续移动！');
      }
    }

    // 向右移动项目
    function moveItemRight(groupIndex, itemIndex) {
      const group = helpData[groupIndex];
      if (itemIndex < group.list.length - 1) {
        const item = group.list.splice(itemIndex, 1)[0];
        group.list.splice(itemIndex + 1, 0, item);
        renderPreview();
        saveData();
      } else if (groupIndex < helpData.length - 1) {
        const confirmMove = confirm('是否将此项目移动到下一个组？');
        if (confirmMove) {
          const item = group.list.splice(itemIndex, 1)[0];
          helpData[groupIndex + 1].list.unshift(item);
          renderPreview();
          saveData();
        }
      } else {
        alert('已经在最后面，无法继续移动！');
      }
    }

    // 向上移动组
    function moveGroupUp(groupIndex) {
      if (groupIndex > 0) {
        const group = helpData.splice(groupIndex, 1)[0];
        helpData.splice(groupIndex - 1, 0, group);
        renderPreview();
        saveData();
      } else {
        alert('已经在最前面，无法继续移动！');
      }
    }

    // 向下移动组
    function moveGroupDown(groupIndex) {
      if (groupIndex < helpData.length - 1) {
        const group = helpData.splice(groupIndex, 1)[0];
        helpData.splice(groupIndex + 1, 0, group);
        renderPreview();
        saveData();
      } else {
        alert('已经在最后面，无法继续移动！');
      }
    }

    // 页面加载时加载 YAML 内容
    window.onload = () => {
      loadYaml(); // 加载 help.yaml
      loadConfig(); // 加载 config.yaml
    };
  </script>
</body>
</html>